package com.lej.push

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.NotificationManagerCompat

/**
 * 检测是否有通知栏权限
 *
 * @author syl
 * @time 2019/5/15 10:35 AM
 */
object NotificationsUtils {
    fun isNotificationEnabled(context: Context): Boolean {
        return NotificationManagerCompat.from(context.applicationContext).areNotificationsEnabled()
    }

    fun openPushIntent(activity: Activity): Intent? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            Intent().apply {
                action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                putExtra(Settings.EXTRA_APP_PACKAGE, activity.packageName)
                putExtra(Settings.EXTRA_CHANNEL_ID, activity.applicationInfo.uid)
            }
        } else {
            toPermissionSetting(activity)
        }
    }

    /**
     * 跳转到权限设置
     *
     * @param activity
     */
    private fun toPermissionSetting(activity: Activity): Intent? {
        return if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            toSystemConfig()
        } else {
            try {
                toApplicationInfo(activity)
            } catch (e: Exception) {
                e.printStackTrace()
                toSystemConfig()
            }
        }
    }

    /**
     * 应用信息界面
     *
     * @param activity
     */
    private fun toApplicationInfo(activity: Activity) = Intent().apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        data = Uri.fromParts("package", activity.packageName, null)
    }

    /**
     * 系统设置界面
     */
    private fun toSystemConfig(): Intent? {
        return try {
            Intent(Settings.ACTION_SETTINGS)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}